import os
import pandas as pd
import numpy as np
import sys
sys.path.append('../../traffic')
sys.path.append('../../config')
import read_traffic as rt
import run_config as rc

def read_recv_log_file(file_name):
    pd_data = pd.read_csv(file_name, header = None)
    pd_data.columns = ['timestamp', 'src', 'dst', 'flag', 'traffic_line', 'filler', 'recv_time']

    # 去掉开头的第一个引号
    pd_data['timestamp'] = pd_data['timestamp'].apply(lambda x: float(x[1:]))
    # 时间变成float
    pd_data['recv_time'] = pd_data['recv_time'].apply(lambda x: float(x))

    return pd_data


def count_src_pkt(df, src_ip, send_cnt, traffic_line):
    # 取出所有统一源头来的包，并重新标注索引
    tmp = df[(df['src'] == src_ip) & (df['traffic_line'] == traffic_line)].reset_index(drop = True)

    recv_cnt = tmp.shape[0]

    loss_num = 0
    if recv_cnt < send_cnt:
        loss_num = send_cnt - recv_cnt
        print('packet loss:', loss_num)
    elif recv_cnt > send_cnt:
        print('recv_cnt:', recv_cnt, ',    send_cnt:', send_cnt)
        print('packet redundancy')
    else:
        diff = tmp[tmp.index != tmp['flag']]
        if diff.empty == False:
            print('out of order')
    
    ct_mean = count_completion_time(tmp)
    # print('mean completion time:', ct_mean)

    return loss_num


def count_completion_time(df):
    df['ct'] = df['recv_time'] - df['timestamp']
    ct_mean = df['ct'].mean()
    return ct_mean
    

if __name__ == "__main__":
    cmd = input('Which folder do you want to count?\n')
    now_path = os.path.abspath(cmd)
    print('Start count', now_path)


    pod_num = rc.pod_num
    which_row = rc.which_row
    traffic_num = rc.a_state_corresponding_traffic_num

    loss_sum = 0
    pkt_sum = 0
    for n in range(traffic_num):
        traffic_line = which_row * traffic_num + n
        print(f'The {traffic_line}th line of traffic file:')
        traffic_arr = rt.get_traffic(f'../../traffic/{pod_num}pod_traffic.csv')[traffic_line]
        completion_time_list = []
        for j in range(pod_num):
            data = read_recv_log_file(f'{now_path}/recv{j+1}.log')
            for i in range(pod_num):
                if i != j:
                    print(f'src->dst : s{i+1}h1->s{j+1}h1, send pkt num:{4 * int(traffic_arr[i][j])}')
                    loss_sum += count_src_pkt(data, f'10.0.{i+1}.1', 4 * int(traffic_arr[i][j]), traffic_line)
                    pkt_sum += 4 * int(traffic_arr[i][j])

            # calculate real completion time
            probe_df = data[data['traffic_line'] == -1]
            completion_time = probe_df['recv_time'] - probe_df['timestamp']
            completion_time_list.append(completion_time.mean())
            print(f'A part of mean completion time:', completion_time.mean())
            print()

    print('total loss sum:', loss_sum)
    print('total pkt sum:', pkt_sum)
    print('loss rate:', loss_sum/ pkt_sum)
    print('The mean completion time:', np.array(completion_time_list).mean())
